package tony.core.jackson

import com.fasterxml.jackson.databind.BeanDescription
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializationConfig
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier
import tony.core.annotation.jackson.JacksonSerializeInject
import tony.core.utils.annotations
import tony.core.utils.asToNotNull

/**
 * jackson 序列化注入 BeanSerializerModifier
 * @author tangli
 * @date 2025/10/31 12:51
 */
public class InjectBeanSerializerModifier(
    private val serializeInjectorFactory: SerializeInjectorFactory,
) : BeanSerializerModifier() {
    override fun modifySerializer(
        config: SerializationConfig,
        beanDesc: BeanDescription,
        serializer: JsonSerializer<*>,
    ): JsonSerializer<*> {
        val annotations =
            beanDesc.beanClass.annotations(JacksonSerializeInject::class.java)

        if (annotations.isEmpty()) {
            return serializer
        }

        val serializeInjectors =
            annotations.map { annotation ->
                val injectorName = annotation.injectorName
                val serializeInjector = serializeInjectorFactory.getSerializeInjector(injectorName)
                if (annotation.params.isNotEmpty()) {
                    serializeInjector.params = annotation.params.toMutableList()
                }
                if (annotation.targetFieldName.isNotEmpty()) {
                    serializeInjector.targetFieldName = annotation.targetFieldName
                }
                serializeInjector
            }

        return JacksonInjectSerializer(
            serializer.asToNotNull(),
            serializeInjectors
        )
    }
}
